package com.dt.sns.elastic;

import org.apache.http.HttpHost;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

public class RestHighLevelClientFactory implements FactoryBean<RestHighLevelClient>, InitializingBean, DisposableBean {

	private static Logger logger = LoggerFactory.getLogger(RestHighLevelClientFactory.class);

	private RestHighLevelClient client;

	private int maxRetryTimeout;

	private String nodes;

	public int getMaxRetryTimeout() {
		return maxRetryTimeout;
	}

	public void setMaxRetryTimeout(int maxRetryTimeout) {
		this.maxRetryTimeout = maxRetryTimeout;
	}

	public String getNodes() {
		return nodes;
	}

	public void setNodes(String nodes) {
		this.nodes = nodes;
	}

	@Override
	public void destroy() throws Exception {
		if (client != null)
			client.close();

	}

	@Override
	public void afterPropertiesSet() throws Exception {
		String[] nodeArray = nodes.split(",");
		HttpHost[] hostList = new HttpHost[nodeArray.length];
		for (int i = 0; i < nodeArray.length; i++) {
			String[] _tmp = nodeArray[i].split(":");
			HttpHost httpHost = new HttpHost(_tmp[0].trim(), Integer.parseInt(_tmp[1].trim()));
			hostList[i] = httpHost;
		}
		RestClientBuilder builder = RestClient.builder(hostList);
		builder.setFailureListener(new RestClient.FailureListener() {
			@Override
			public void onFailure(Node node) {
				logger.warn("connect failed.the host:" + node.getHost().getHostName());
			}
		});
		client = new RestHighLevelClient(builder);
	}

	@Override
	public RestHighLevelClient getObject() throws Exception {
		return client;
	}

	@Override
	public Class<?> getObjectType() {
		return RestHighLevelClient.class;
	}

	@Override
	public boolean isSingleton() {
		return false;
	}

}